import { useNavigate } from 'react-router-dom'
import { useSignUpMutation } from '../../api/userApiSlice'
import { Controller, SubmitHandler, useForm } from 'react-hook-form'
import * as yup from 'yup'
import { yupResolver } from '@hookform/resolvers/yup'
import { FC } from 'react'
import { Box, TextField, Typography } from '@mui/material'
import { LoadingButton } from '@mui/lab'
import styled from '@emotion/styled'
import { useAppDispatch } from '../../hooks'
import { alertSlice } from '../../store/reducers/slices/alertSlice'
import { TUser } from '../../store/types'

export type SignUpFormValues = Pick<TUser, 'email' | 'group' | 'password'>

const signUpFormSchema = yup.object({
	email: yup.string().email().required(),
	group: yup
		.string()
		.lowercase()
		.matches(
			/ra-\d{1,4}?$/,
			'Группа должна быть в формате ra-####, где #### от 1 до 9999'
		)
		.required()
		.strict(),
	password: yup.string().min(6).max(24).required(),
})

const StyledContainer = styled('div')(() => ({
	display: 'flex',
	flexDirection: 'column',
	width: '420px',
	padding: '16px',
	borderRadius: '20px',
	background: '#FFFFFF',
}))

const StyledTypographyHeader = styled(Typography)(() => ({
	fontFamily: 'Nunito',
	fontSize: '28px',
	fontWeight: '800',
	lineHeight: '32px',
	letterSpacing: '0em',
	textAlign: 'left',
}))

const StyledTypographyInform = styled(Typography)(() => ({
	fontFamily: 'Nunito',
	fontSize: '12px',
	fontWeight: '400',
	lineHeight: '14px',
	letterSpacing: '0em',
	textAlign: 'left',
	color: '#7B8E98',
}))

const StyledButton = styled(LoadingButton)(() => ({
	display: 'flex',
	alignSelf: 'center',
	marginTop: '16px',
	width: '356px',
	height: '48px',
	borderRadius: '55px',
	background: '#FFE44D',
	border: '0px',
	'&': {
		color: '#1A1A1A',
		textTransform: 'none',
	},
}))

export const SignUpForm: FC = () => {
	const dispatch = useAppDispatch()
	const navigate = useNavigate()
	const [signUpRequestFn] = useSignUpMutation()

	const {
		control,
		handleSubmit,
		formState: { errors, isValid, isSubmitting, isSubmitted },
	} = useForm<SignUpFormValues>({
		defaultValues: {
			email: '',
			group: '',
			password: '',
		},
		resolver: yupResolver(signUpFormSchema),
	})
	function onSuccess() {
		dispatch(alertSlice.actions.setType('success'))
		dispatch(
			alertSlice.actions.setText(
				'Вы успешно зарегистрированы! Войдите в систему'
			)
		)
		dispatch(alertSlice.actions.setIsOpen(true))
		setTimeout(() => dispatch(alertSlice.actions.setIsOpen(false)), 5000)
		navigate('/signin')
	}

	function onError() {
		dispatch(alertSlice.actions.setType('error'))
		dispatch(
			alertSlice.actions.setText(
				'Неизвестная ошибка при регистрации пользователя'
			)
		)
		dispatch(alertSlice.actions.setIsOpen(true))
		setTimeout(() => dispatch(alertSlice.actions.setIsOpen(false)), 5000)
	}

	const submitHandler: SubmitHandler<SignUpFormValues> = async (values) => {
		let response
		try {
			response = await signUpRequestFn(values)
			if ('data' in response) {
				onSuccess()
			} else if ('error' in response) {
				onError()
			}
		} catch (error) {
			onError()
		}
	}

	return (
		<StyledContainer>
			<StyledTypographyHeader>Регистрация</StyledTypographyHeader>
			<Box
				component='form'
				onSubmit={handleSubmit(submitHandler)}
				noValidate
				sx={{ mt: 1 }}
			>
				<Controller
					name='email'
					control={control}
					render={({ field }) => (
						<TextField
							margin='normal'
							label='Email Address'
							type='email'
							fullWidth
							required
							autoComplete='email'
							error={!!errors.email?.message}
							helperText={errors.email?.message}
							{...field}
						/>
					)}
				/>
				<Controller
					name='group'
					control={control}
					render={({ field }) => (
						<TextField
							label='Group Id'
							type='text'
							margin='normal'
							error={!!errors.group?.message}
							helperText={errors.group?.message}
							fullWidth
							required
							{...field}
						/>
					)}
				/>
				<Controller
					name='password'
					control={control}
					render={({ field }) => (
						<TextField
							label='Password'
							type='password'
							error={!!errors.password?.message}
							helperText={errors.password?.message}
							margin='normal'
							fullWidth
							required
							{...field}
						/>
					)}
				/>
				<StyledTypographyInform>
					Регистрируясь на сайте, вы соглашаетесь с нашими Правилами и Политикой
					конфиденциальности и соглашаетесь на информационную рассылку.
				</StyledTypographyInform>
				<StyledButton
					type='submit'
					disabled={isSubmitted && (!isValid || isSubmitting)}
					loading={isSubmitting}
					fullWidth
					variant='outlined'
					sx={{ mt: 3, mb: 2 }}
				>
					Зарегистрироваться
				</StyledButton>
				<StyledButton type='button' onClick={() => navigate('/signin')}>
					Войти
				</StyledButton>
			</Box>
		</StyledContainer>
	)
}
